package com.sgq.vue.redis.impl;

import com.alibaba.fastjson.JSON;
import com.sgq.vue.redis.CommonSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * @author: 83778
 * @date: 2023-12-24 16:58
 * @desc:
 */
@Component
public class CommonJacksonSerializer implements CommonSerializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonJacksonSerializer.class);

    public static final Charset DEFAULT_CHARSET_INSTANCE = Charset.forName("UTF-8");

    public CommonJacksonSerializer() {

    }

    @Override
    public byte[] serialize(Type var1, Object ob) {
        if (ob == null) {
            return new byte[0];
        } else {
            String result = JSON.toJSONString(ob);
            return StringUtils.isEmpty(result) ? new byte[0] : result.getBytes(DEFAULT_CHARSET_INSTANCE);
        }
    }

    @Override
    public Object  deserialize(byte[] bytes, Type type) {
        try {
            return JSON.parseObject(new String(bytes), type);
        } catch (Exception var4) {
            LOGGER.error(var4.getMessage(), var4);
            return null;
        }
    }
}

